import { randomUUID } from '../../../../mapUtils/RandomUtil';
import Layer from '../../constant/Layer';

/**
 * 地块组件
 */
class Block {
  constructor(_) {
    this.tool = _;
    this.id = randomUUID();
    this.layeridPrefix = _.layeridPrefix;
    this.events = {
      onComplete: () => { }
    };
    this.init();
  }

  /**
   * 获取地图对象
   * @ignore
   */
  getMap() {
    return this.tool.getMap();
  }

  /**
   * 获取工具箱
   * @param {String} toolname 工具箱名称
   * @ignore
   */
  getTool(toolname) {
    return this.tool.getTool(toolname);
  }

  /**
   * 设置事件方法
   * @param {*} _events 事件方法
   */
  setEvents(_events) {
    for (let key in _events) {
      this.events[key] = _events[key];
    }
  }

  /**
   * 加载地块
   * @param {features} features 地块图形数据
   * @param {Boolean} fitBound 是否定位
   */
  render(features, fitBound) {
    this.totalFeatures = this.loadedFeatures = features;
    let featureCollection = window.turf.featureCollection(this.loadedFeatures);
    this.getMap().getSource(this._SourceId).setData(featureCollection);
    if (fitBound && features.length > 0) {
      let polygon = window.turf.envelope(featureCollection);
      this.getTool('BaseMapTool').fitBounds(window.turf.bbox(polygon));
    }
  }

  /**
   * 绘制地块
   * @param {*} events 绘制事件
   */
  draw(events) {
    if (events) {
      this.setEvents(events);
    }
    this.getTool('EditTool').changeMode('snap_polygon');
    this.getTool('EditTool').enableSnap();
    this.getTool('EditTool').setSnapFeatures(this.totalFeatures);
    this.getTool('EditTool').events.onSelectionchange = (e) => {
      if (e.features.length === 0) {
        let data = this.getTool('EditTool').getAll();
        this.events.onComplete(data.features[0]);
        this.getTool('EditTool').reset();
      }
    };
  }

  /**
   * 编辑地块
   * @param {feature} feature 地块图形数据
   * @param {*} events 编辑事件
   */
  edit(feature, events) {
    if (events) {
      this.setEvents(events);
    }
    // 将正在编辑的区域从原图层中隐藏
    this.loadedFeatures = this.totalFeatures.filter((region) => region.properties.oid !== feature.properties.oid);
    this.getMap().getSource(this._SourceId).setData(turf.featureCollection(this.loadedFeatures));
    // 加载编辑区域
    let id = feature.id = feature.properties.id = feature.properties.oid;
    this.getTool('EditTool').editFeatures([feature]);
    this.getTool('EditTool').changeMode('direct_select', { featureId: id });
    this.getTool('EditTool').enableSnap();
    this.getTool('EditTool').setSnapFeatures(this.totalFeatures);
    this.getTool('EditTool').events.onSelectionchange = (e) => {
      if (e.features.length === 0) {
        let data = this.getTool('EditTool').getAll();
        this.events.onComplete(data.features[0]);
        this.getTool('EditTool').reset();
      }
    };
  }

  /**
   * 切换地块颜色
   * @param {Number} oid 地块Id
   * @param {String} color 地块颜色
   */
  changeBlockColor(oid, color) {
    this.loadedFeatures.forEach((item) => {
      if (item.properties.oid === oid) {
        item.properties.color = color;
      }
    });
    this.getMap().getSource(this._SourceId).setData(turf.featureCollection(this.loadedFeatures));
  }

  /**
   * 清空图层
   */
  clear() {
    this.totalFeatures = [];
    this.loadedFeatures = [];
    this.getMap().getSource(this._SourceId).setData(turf.featureCollection([]));
  }

  /**
   * 重置编辑工具
   */
  reset() {
    this.getTool('EditTool').reset();
  }

  /**
   * 初始化
   * @ignore
   */
  init() {
    this.initId();
    this.initLayer();
  }

  /**
   * 初始化图层Id
   * @ignore
   */
  initId() {
    // 数据源
    this._SourceId = this.layeridPrefix + '_source_' + this.id;
    // 图层
    this._PolygonLayerId = this.layeridPrefix + '_Polygon' + this.id;
    this._StrokeLayerId = this.layeridPrefix + '_PolygonStroke' + this.id;
    this._LabelLayerId = this.layeridPrefix + '_PolygonLabel' + this.id;
  }

  /**
   * 初始化图层
   * @ignore
   */
  initLayer() {
    // 初始化数据源
    if(!this.tool.getMap().getSource(this._SourceId)) {
      this.tool.getMap().addSource(this._SourceId, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      });
    }
    // 初始化图层
    if(!this.tool.getMap().getLayer(this._PolygonLayerId)) {
      this.tool.getMap().addLayer({
        id: this._PolygonLayerId,
        type: 'fill',
        source: this._SourceId,
        filter: ['all', ['==', '$type', 'Polygon']],
        paint: {
          'fill-color': ['get', 'color'],
          'fill-opacity': ['get', 'opacity']
        }
      });
    }
    if(!this.tool.getMap().getLayer(this._StrokeLayerId)) {
      this.tool.getMap().addLayer({
        id: this._StrokeLayerId,
        type: 'line',
        source: this._SourceId,
        filter: ['all', ['==', '$type', 'Polygon']],
        paint: {
          'line-color': ['get', 'line-color'],
          'line-opacity': ['get', 'line-opacity'],
          'line-width': ['get', 'line-width']
        }
      });
    }
    if(!this.tool.getMap().getLayer(this._LabelLayerId)) {
      this.tool.getMap().addLayer({
        id: this._LabelLayerId,
        type: 'symbol',
        source: this._SourceId,
        filter: ['all', ['==', '$type', 'Point']],
        layout: {
          'icon-anchor': 'center',
          'text-field': '{' + Layer.GlobalMarkLabelField + '}',
          'text-size': 12,
          'text-font': ['Microsoft YaHei Regular'],
          'text-offset': [0, 0],
          'text-max-width': 8,
          'text-allow-overlap': false,
          'text-ignore-placement': false,
          'text-anchor': 'top'
        },
        paint: {
          'text-color': '#555252',
          'text-halo-color': '#FFFFFF',
          'text-halo-width': 1.33333
        }
      });
    }
  }
}

export default Block;